package com.newlink.building.userinfo.activity

import android.annotation.SuppressLint
import android.app.ProgressDialog
import android.content.Context
import android.content.Intent
import android.graphics.drawable.ColorDrawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.PopupWindow
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.newlink.building.common_base.base.NL_BaseMvpActivity
import com.newlink.building.common_base.constant.Base_DeviceType
import com.newlink.building.common_base.ext.clickDelay
import com.newlink.building.common_base.model.bean.DeviceData
import com.newlink.building.common_base.model.bean.DeviceListRequest
import com.newlink.building.common_base.model.bean.FamilyListData
import com.newlink.building.common_base.model.bean.FamilyManagementListData1
import com.newlink.building.common_base.utils.DialogUtil
import com.newlink.building.common_base.utils.NLog
import com.newlink.building.common_base.utils.ToastUtils
import com.newlink.building.common_base.widget.CustomInputDialog
import com.newlink.building.common_base.widget.SpaceItemDecoration
import com.newlink.building.userinfo.R
import com.newlink.building.userinfo.adapter.Module_UserInfo_AreaSelectionAdapter
import com.newlink.building.userinfo.adapter.Module_UserInfo_MemberPickAdapter
import com.newlink.building.userinfo.bean.Module_UserInfo_CheckBean
import com.newlink.building.userinfo.databinding.ActivityAuthParamsBinding
import com.newlink.building.userinfo.mvp.Module_UserInfo_AuthParamPresenter
import com.newlink.building.userinfo.mvp.contract.Module_UserInfo_AuthParamContract


/**
 * @Author: Jake
 * @Date: 2023-12-26
 * @Description:
 */
class Module_UserInfo_AuthParamActivityNL : NL_BaseMvpActivity<Module_UserInfo_AuthParamContract.View, Module_UserInfo_AuthParamContract.Presenter>(),
    Module_UserInfo_AuthParamContract.View {

    val TYPE_NAME: Int = 10000

    private var mUserName: String = ""
    private var mUserId: String = ""
    private var deviceBeans = arrayListOf<Module_UserInfo_CheckBean>()
    private var mSelectItem: MutableList<Module_UserInfo_CheckBean>? = null
    private var mWaitProgressDialog: ProgressDialog? = null
    private var mNeedShowDialog = false
    private var bottomSheetDialog: BottomSheetDialog? = null
    private val MAX_LIMIT = 1000
    private var lastClickTime: Long = 0L

    private var mFamilyListData: MutableList<FamilyManagementListData1> = mutableListOf()

//    override fun attachLayoutRes(): Int = R.layout.activity_auth_params

    private lateinit var mBinding: ActivityAuthParamsBinding
    override fun attachLayoutRes(): View {
        mBinding = ActivityAuthParamsBinding.inflate(layoutInflater)
        return mBinding.root
    }

    override fun createPresenter(): Module_UserInfo_AuthParamContract.Presenter = Module_UserInfo_AuthParamPresenter()

    override fun initData() {
        showWaitingDialog(getString(R.string.auth_face_load_area))
        mPresenter?.getFamilyMember(accessToken)
    }

    override fun onGetFamilyMemberSuccess(data: FamilyListData?) {
        mFamilyListData = data?.list!!
        mPresenter?.getAvailableArea(
            DeviceListRequest(accessToken, 1, MAX_LIMIT, "", null)
        )
    }

    override fun onGetFamilyMemberFailed(msg: String) {
        hideLoading()
    }

    override fun initView() {

        findViewById<TextView>(R.id.tv_title_bar_center).text =
            resources.getText(R.string.auth_face)

        mBinding.authFaceName.setOnClickListener {
//            showCustomInputDialog(
//                getString(R.string.auth_face_input_name),
//                TYPE_NAME,
//                EditorInfo.TYPE_CLASS_TEXT
//            )
            showFamilySelectDialog()
        }
        mBinding.authFaceArea.setOnClickListener {
            if (deviceBeans.size == 0) {
                showWaitingDialog(getString(R.string.auth_face_load_area))
                NLog.e("[jake]... click is auth_card_area")
                mNeedShowDialog = true
                mPresenter?.getAvailableArea(
                    DeviceListRequest(accessToken, 1, MAX_LIMIT, "", null)
                )
            } else {
                NLog.e("[jake]... show area dialog")
                showBottomSheetDialog(this, deviceBeans)
            }
        }
        mBinding.btnAuthFaceSubmit.clickDelay {
            NLog.e("[jake]... click is btn_auth_card_submit")

            if (mUserName.isEmpty() || mUserId.isEmpty()) {
                ToastUtils.showTextToast(this, getString(R.string.auth_face_input_name))
                return@clickDelay
            }

            if (mSelectItem == null || mSelectItem!!.size <= 0) {
                ToastUtils.showTextToast(this, getString(R.string.auth_card_et_input_area))
                return@clickDelay
            }

            if (System.currentTimeMillis() - lastClickTime < 2000) {
                return@clickDelay
            }

            lastClickTime = System.currentTimeMillis()
            val availableArea = mutableListOf<String>()
            for (item in mSelectItem!!) {
                availableArea.add(item.value)
            }
            NLog.e("[jake]... cardName is $mUserName")
            NLog.e("[jake]... availableArea is $availableArea")

            val resultIntent = Intent()
            resultIntent.putExtra("face_name", mUserName)
            resultIntent.putExtra("face_user_id", mUserId)
            resultIntent.putExtra("face_area", availableArea.toTypedArray())
            setResult(RESULT_OK, resultIntent)
            finish()
        }

    }

    private fun showCustomInputDialog(
        tittle: String,
        type: Int,
        inputType: Int = EditorInfo.TYPE_CLASS_TEXT,
    ) {
        val customInputDialog = CustomInputDialog(this@Module_UserInfo_AuthParamActivityNL)
        customInputDialog.setTitle(tittle).setText(
            mUserName.ifBlank {
                ""
            }
        ).setType(type)
            .setInputType(inputType)
            .setNegativeButton(
                listener = object : CustomInputDialog.OnClickListener {
                    override fun onClick(type: Int, inputText: String) {
                        customInputDialog.dismiss()
                    }
                }
            ).setPositiveButton(
                listener = object : CustomInputDialog.OnClickListener {
                    override fun onClick(type: Int, inputText: String) {
                        when (type) {
                            TYPE_NAME -> {
                                mUserName = inputText
                                mBinding.tvAuthFaceName.text = inputText
                            }
                        }
                        customInputDialog.dismiss()
                    }

                }

            )
        customInputDialog.show()
    }

    @SuppressLint("InflateParams", "MissingInflatedId")
    private fun showBottomSheetDialog(context: Context, cbs: MutableList<Module_UserInfo_CheckBean>) {
        var selectIndex = 0
        bottomSheetDialog = BottomSheetDialog(context, R.style.BottomSheetDialog)
        bottomSheetDialog?.setCanceledOnTouchOutside(false)
        val view = LayoutInflater.from(context).inflate(R.layout.dialog_auth_card_area, null, false)
        val recyclerView = view.findViewById<RecyclerView>(R.id.recyclerView)
        view.findViewById<TextView>(R.id.tv_cancel).setOnClickListener {
            bottomSheetDialog?.dismiss()
        }
        val title = view.findViewById<TextView>(R.id.tv_title)
        title.text = resources.getString(R.string.auth_card_key_input_area)

        if (mSelectItem != null) {
            cbs.forEach {
                it.isChecked = false
                mSelectItem!!.forEach { selectItem ->
                    if (selectItem.name == it.name) {
                        it.isChecked = true
                    }
                }
            }
        }

        view.findViewById<TextView>(R.id.tv_confirm).setOnClickListener {
            if (cbs.size > 0) {
                mSelectItem = cbs.filter {
                    it.isChecked
                }.toMutableList()
                var names = ""
                for ((index, item) in mSelectItem!!.withIndex()) {
                    var tempName = item.name
                    if (tempName.length > 16) {
                        tempName = tempName.substring(0, 15).plus("...")
                    }
                    names += if (index == mSelectItem!!.size - 1) {
                        tempName
                    } else {
                        "$tempName/"
                    }
                }
                if (mBinding.tvAuthCardArea != null) {
                    mBinding.tvAuthCardArea.text = names
                } else {
                    view.findViewById<TextView>(R.id.tv_auth_card_area).text = names
                }
//                tv_auth_card_area.text = names
            }
            bottomSheetDialog?.dismiss()
        }

        val mAdapter = Module_UserInfo_AreaSelectionAdapter(cbs)
        recyclerView.adapter = mAdapter
        recyclerView.addItemDecoration(SpaceItemDecoration(context))
        mAdapter.setOnItemClickListener { _, _, position ->
            NLog.e("[jake].... card select $position")
            selectIndex = position
            mAdapter.setSelectItem(position)
        }

        bottomSheetDialog?.setContentView(view)
        bottomSheetDialog?.show()
    }

    override fun refreshDeviceList(total: Int, list: MutableList<DeviceData>) {
        hideLoading()
        if (bottomSheetDialog != null && bottomSheetDialog?.isShowing == true) {
            return //如果当前dialog正在显示，则不刷新
        }
        NLog.e("[jake]... refreshDeviceList .....")
        deviceBeans.clear()
        for (item in list) {
            if (item.devType == Base_DeviceType.DOORPHONE.code) {
                deviceBeans.add(Module_UserInfo_CheckBean(item.devName.orEmpty(), item.mac, 0, true))
            }
        }
        if (mNeedShowDialog) {
            mNeedShowDialog = false
            showBottomSheetDialog(this, deviceBeans)
        }
    }

    private fun showFamilySelectDialog() {
        val popupWindow = PopupWindow(this)
        val view: View = LayoutInflater.from(this).inflate(R.layout.popup_member_pick, null)
        val recyclerView = view.findViewById<RecyclerView>(R.id.recyclerView)
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.addItemDecoration(SpaceItemDecoration(this))
        val accountList = mFamilyListData
        val accountPickAdapter = Module_UserInfo_MemberPickAdapter(accountList)
        recyclerView.adapter = accountPickAdapter
        accountPickAdapter.setOnItemChildClickListener { _, _, position ->
            mBinding.tvAuthFaceName.text = accountList[position].name
            mUserName = accountList[position].name
            mUserId = accountList[position].id
            popupWindow.dismiss()
        }

        popupWindow.width = mBinding.authFaceName.width
        popupWindow.height = ViewGroup.LayoutParams.WRAP_CONTENT
        popupWindow.contentView = view
        popupWindow.isFocusable = true
        popupWindow.setBackgroundDrawable(ColorDrawable(getColor(R.color.transparent)))
        popupWindow.elevation = 3f
        popupWindow.showAsDropDown(mBinding.authFaceName, 0, 4)
    }

    private fun showWaitingDialog(msg: String) {
        hideWaitingDialog()
        mWaitProgressDialog = DialogUtil.getWaitDialog(this@Module_UserInfo_AuthParamActivityNL, msg)
        mWaitProgressDialog?.setProgressStyle(ProgressDialog.STYLE_SPINNER)
        mWaitProgressDialog?.show()
    }

    private fun hideWaitingDialog() {
        if (mWaitProgressDialog?.isShowing == true) {
            mWaitProgressDialog?.dismiss()
            mWaitProgressDialog = null
        }
    }

    override fun hideLoading() {
        super.hideLoading()
        hideWaitingDialog()
    }

    override fun onDestroy() {
        super.onDestroy()
        lastClickTime = 0
    }
}